package com.yunxin.core.utils.infra.utils;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @author zero°
 * @since 2023-05-25
 */
@Slf4j
public enum AesUtils {

    /**
     * 实例
     */
    X;

    private static final String S_KEY  = "yx_aes";

    private SecretKeySpec getSecretKeySpec(String key){
        if (StringUtils.isBlank(key)) {
            key = S_KEY;
        }
        byte[] raw = Arrays.copyOf(key.getBytes(UTF_8), 16);
        return new SecretKeySpec(raw, "AES");
    }

    /**
     * AES 解密
     * @param content content
     * @param key key
     * @return result
     */
    public String decrypt(String content, String key) {
        if (CharSequenceUtil.isEmpty(content)) {
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(key));
            //先用base64解密
            byte[] encrypted1 = Base64.getDecoder().decode(content);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, UTF_8);
        } catch (Exception e) {
            log.error("AesUtils.decrypt解密异常", e);
            return null;
        }
    }

    /**
     * AES 加密
     * @param content content
     * @param key key
     * @return result
     */
    public String encrypt(String content, String key) {
        try {
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(key));
            byte[] encrypted = cipher.doFinal(content.getBytes(UTF_8));
            //此处使用BASE64做转码功能，同时能起到2次加密的作用。
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            log.error("AesUtils.encrypt加密异常", e);
        }
        return null;
    }

}
